<template>
  <n-select
    v-model:value="localValue"
    :options="options"
    :placeholder="placeholder"
    :disabled="disabled || loading"
    :filterable="filterable"
    :clearable="clearable"
    :multiple="multiple"
    :loading="loading"
    :render-option="renderOption"
    v-bind="$attrs"
    @update:value="handleUpdate"
    @clear="handleClear"
  >
    <template #prefix>
      <slot name="prefix" />
    </template>
    <template #suffix>
      <slot name="suffix" />
    </template>
  </n-select>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: [String, Number, Array],
  options: {
    type: Array,
    default: () => []
  },
  placeholder: {
    type: String,
    default: ''
  },
  disabled: Boolean,
  loading: Boolean,
  filterable: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: true
  },
  multiple: Boolean,
  renderOption: Function
})

const emit = defineEmits(['update:modelValue', 'clear'])

const localValue = ref(props.modelValue)

watch(() => props.modelValue, (newValue) => {
  localValue.value = newValue
})

const handleUpdate = (value) => {
  localValue.value = value
  emit('update:modelValue', value)
}

const handleClear = () => {
  localValue.value = props.multiple ? [] : null
  emit('update:modelValue', props.multiple ? [] : null)
  emit('clear')
}
</script>